package com.dawnling.greendaodemo;

import androidx.appcompat.app.AppCompatActivity;

import android.database.Cursor;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.dawnling.greendaodemo.app.MyApplication;
import com.dawnling.greendaodemo.bean.UserBean;
import com.dawnling.greendaodemo.bean.UserChildBean;
import com.dawnling.greendaodemo.bean.UserThreeChildBean;
import com.dawnling.greendaodemo.greendao.gen.DaoSession;
import com.dawnling.greendaodemo.greendao.gen.UserBeanDao;

import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.WhereCondition;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private String[] urlStr = new String[]{"http://fanyi.youdao.com/", "https://www.baidu.com/?tn=62095104_8_oem_dg", "https://github.com/"};
    private UserBeanDao noteDao;
    private Query<UserBean> notesQuery;
    private TextView tvContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvContent = findViewById(R.id.tvContent);
        tvContent.setMovementMethod(ScrollingMovementMethod.getInstance());
        // get the note DAO
        DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
        noteDao = daoSession.getUserBeanDao();

        notesQuery = noteDao.queryBuilder().orderAsc(UserBeanDao.Properties.Data).build();
        updateNotes();
    }

    private void updateNotes() {
        List<UserBean> notes = notesQuery.list();
        tvContent.setText(notes.toString());
    }

    /**
     * 添加数据
     */
    public void btnAdd(View v){
        noteDao.deleteAll();
        for (int i = 0; i < 20; i++){
            UserBean userBean = new UserBean();
            userBean.setName("名称:" + (i+1));
            if (i%2 == 0) {
                userBean.setData("2019-11-11");
                userBean.setUrl(urlStr[0]);
            }else if (i%3 == 0) {
                userBean.setData("2018-11-11");
                userBean.setUrl(urlStr[1]);
            }else {
                userBean.setData("2020-12-12");
                userBean.setUrl(urlStr[2]);
            }
            noteDao.insert(userBean);
        }
        updateNotes();
    }

    /**
     * 测试添加多层嵌套数据
     * @param v
     */
    public void btnAddComplex(View v){
        noteDao.deleteAll();
        //字符串数组
        List<String> list = new ArrayList<>();
        if (list != null) list.clear();
        list.add("你好1");
        list.add("你好2");
        list.add("你好3");
        list.add("你好4");
        //对象数组
        List<UserChildBean> list1 = new ArrayList<>();
        if (list1 != null) list1.clear();
        list1.add(new UserChildBean("父亲1", "母亲1", list, new UserThreeChildBean("三娃1")));
        list1.add(new UserChildBean("父亲2", "母亲2", list, new UserThreeChildBean("三娃2")));
        list1.add(new UserChildBean("父亲3", "母亲3", list, new UserThreeChildBean("三娃3")));
        for (int i = 0; i < 20; i++){
            UserBean userBean = new UserBean();
            userBean.setName("名称:" + (i+1));
            if (i%2 == 0) {
                userBean.setData("2019-11-11");
                userBean.setUrl(urlStr[0]);
            }else if (i%3 == 0) {
                userBean.setData("2018-11-11");
                userBean.setUrl(urlStr[1]);
            }else {
                userBean.setData("2020-12-12");
                userBean.setUrl(urlStr[2]);
            }
            userBean.setList(list);
            userBean.setUserChildBeanList(list1);
            userBean.setUserChildBean(new UserChildBean("fatherName"+i, "motherName"+i));
            noteDao.insert(userBean);
        }
        updateNotes();
    }

    /**
     * 分组1
     */
    public void btnGroup(View v){
        //查询全部数据
        List<UserBean> listAll = noteDao.loadAll();
        //查询数量
        long count = noteDao.count();
        List<UserBean> list = noteDao.queryBuilder()
                //orderDesc根据某字段，降序---descending。orderAsc根据某字段，升序---ascending 默认是升序
                .orderDesc(UserBeanDao.Properties.Data)
                .where(new WhereCondition.StringCondition("1 GROUP BY " + UserBeanDao.Properties.Data.name))//根据日期分组或者写死："1 GROUP BY data"
                .list();

        Map<String, List<UserBean>> map = new HashMap<>();
        if (map != null) map.clear();
        for (UserBean bean: list){
            List<UserBean> beanList = noteDao.queryBuilder().where(UserBeanDao.Properties.Data.eq(bean.getData())).list();
            map.put(bean.getData(), beanList);
        }
        tvContent.setText(list.toString() +"\n\n结果：\n" + map.toString());
    }
    /**
     * 分组2
     */
    public void btnGroup2(View v){
        String sql = "SELECT DISTINCT " + UserBeanDao.Properties.Data.columnName
                + " FROM " + UserBeanDao.TABLENAME
                + " ORDER BY " + UserBeanDao.Properties.Data.name;
        Cursor c = MyApplication.getInstance().getDaoSession().getDatabase().rawQuery(sql, new String[]{});
        List<String> result = new ArrayList<>();
        try {
            if (c != null) {
                if (c.moveToFirst()) {
                    do {
                        result.add(c.getString(0));
                    } while (c.moveToNext());
                }
            }
        } finally {
            if (c != null) c.close();
        }
        Log.e("数据库", "结果：\n" + result.toString());//结果：[2019-11-11, 2020-12-12, 2018-11-11]
    }
}
